package com.wongsir.step4.tiny_ioc.factory;

import java.lang.reflect.Field;

import com.wongsir.step4.tiny_ioc.BeanDefinition;
import com.wongsir.step4.tiny_ioc.PropertyValue;

/**
 * 可自动装配内容的BeanFactory
 * @author wongsir
 * @date 2018年9月14日
 */
public class AutowireCapableBeanFactory extends AbstractBeanFactory{

	@Override
	protected Object doCreateBean(BeanDefinition beanDefinition) throws Exception {
		Object bean = createBeanInstance(beanDefinition);
		applyPropertyValues(bean,beanDefinition);
		return null;
	}

	protected Object createBeanInstance(BeanDefinition beanDefinition) throws InstantiationException, IllegalAccessException {
		return beanDefinition.getBeanClass().newInstance();
	}
	
	protected void applyPropertyValues(Object bean, BeanDefinition mbd) throws Exception{
		for(PropertyValue propertyValue : mbd.getPropertyValues().getPropertyValues()) {
			Field declaredField = bean.getClass().getDeclaredField(propertyValue.getName());
			declaredField.setAccessible(true);
			declaredField.set(bean, propertyValue.getValue());
		}
	}

}
